#!/usr/bin/poython3.6
# conding:utf-8
import socket
import uuid
import netifaces
import ipaddress
import os


class Messgae:
    def __init__(self, myidpath):
        if os.path.exists(myidpath):  # 如果存在
            with  open(myidpath)  as  f:
                self.id = f.readline().strip()
        else:
            self.id = uuid.uuid4().hex
            with open(myidpath, 'w')  as f:
                f.write(self.id)

    def get_ipaddress(self):
        address = []
        for p in netifaces.interfaces():  # 获取网口列表
            n = netifaces.ifaddresses(p)  # 获取字典
            if n.get(2):  # 查看是否存在ipv4地址
                for ip in n[2]:  # 此处获取对应列表的值
                    if ip['addr']:  # 查看ip地址是否存在
                        ip = ipaddress.ip_address(ip['addr'])
                        if ip.is_reserved or ip.is_multicast or ip.is_link_local or ip.is_loopback:
                            continue
                        address.append(str(ip))
        return address

    def hearbeat(self):
        return {
            "type": "hearbeat",
            "payload": {
                "ip": self.get_ipaddress(),
                "hostname": socket.gethostname(),
                "id": self.id
            }
        }

    def reg(self):
        return {
            "type": "register",
            "payload": {
                "ip": self.get_ipaddress(),
                "hostname": socket.gethostname(),
                "id": self.id
            }
        }

    def result(self, task_id, code, output):  # 返回数据至web端，处理相关数据执行结果的返回
        return {
            "type": "result",
            "payload": {
                "id": task_id,
                "agent_id": self.id,
                "code": code,
                "output": output
            }
        }


if __name__ == "__main__":
    msg = Messgae('/var/log/mschedule/uuid')
    print(msg.reg())
